/*
 * Copyright 2009 Prime Technology.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.primefaces.optimus.aop;

import java.lang.reflect.Method;

import javax.faces.context.FacesContext;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.primefaces.optimus.auth.AuthContext;
import org.primefaces.optimus.auth.Authorize;
import org.primefaces.optimus.util.Constants;

/**
 * Method interceptor that makes a security check before executing a method
 */
public class AuthorizationMethodInterceptor implements MethodInterceptor {

	public Object invoke(MethodInvocation methodInvocation) throws Throwable {
		Method method = methodInvocation.getMethod();
		Authorize authorize = method.getAnnotation(Authorize.class);
		String[] roles = authorize.value().split(",");
		AuthContext authContext = getAuthContext();
		
		for(String role : roles) {
			if(authContext.isUserInRole(role.trim()))
				continue;
			else
				throw new SecurityException("User:\"" + authContext.getUsername() + "\" does not have the granted authority to execute method:\"" + method.getName() + "\" of " + method.getDeclaringClass().getName());	
		}
		
		return methodInvocation.proceed();
	}
	
	protected AuthContext getAuthContext() {
		return (AuthContext) FacesContext.getCurrentInstance().getExternalContext().getApplicationMap().get(Constants.AUTHCONTEXT_KEY);
    }
}